package ClientFront.Net;

import ClientFront.Listeners.MsgReciver;
import ClientFront.NetMsg;
import Server.ServerConsts;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.management.ThreadInfo;
import java.net.ConnectException;
import java.net.Socket;
import java.net.SocketException;

public class NetMsgDealer implements Runnable,MsgReciver{
    boolean isRunning = false;
    ConnectionInfo cinfo;
    String userName;
    Socket socket;
    ObjectInputStream input;
    ObjectOutputStream output;
    MsgReciver msgReciver;
    public NetMsgDealer(){

    }

    public void setLocalPort(int port){
        cinfo.setMyPort(port);
    }
    public void setServerPort(int port){
        cinfo.setServerPort(port);
    }
    public void setLocalIpAddress(String ipAddress){
        cinfo.setLocalIPAddress(ipAddress);
    }
    public void setServerIPAddress(String ipAddress){
        cinfo.setServerIpAddress(ipAddress);
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setMsgReciver(MsgReciver msgReciver) {
        this.msgReciver = msgReciver;
    }

    public void setConnectionInfo(ConnectionInfo cinfo){
        this.cinfo = cinfo;
    }

    public boolean init(){
        //判断！
        isRunning = true;
        System.out.println("正在连接到"+cinfo.getServerAddress()+":"+cinfo.getServerPort());
        try{
            socket = new Socket(cinfo.getServerAddress(),cinfo.getServerPort());

            output = new ObjectOutputStream(socket.getOutputStream());
            output.writeUnshared(new NetMsg(MsgTypeEnum.LINKTEST,userName));
            output.flush();
            input = new ObjectInputStream(socket.getInputStream());


            msgReciver.sendMsg(new NetMsg(MsgTypeEnum.CLIENT_TIP,"已创建连接...等待主机回应"));

            NetMsg msg =  (NetMsg)input.readUnshared();
            msgReciver.sendMsg(msg);
            return true;
        }catch (ConnectException e){
            System.out.println("无法连接到目标主机,连接被拒绝，可能没有开启服务器监听端口");
            msgReciver.sendMsg(new NetMsg(MsgTypeEnum.LINKERROR,"无法连接到目标主机"));
            isRunning = false;
            return false;
        }catch (Exception e){}
        return true;
    }

    @Override
    public void sendMsg(NetMsg msg) {
        try{
            output.writeUnshared(msg);
            output.flush();
            System.out.println("发送消息："+msg.getMsgType().name());
        }catch (IOException what){}
    }

    /**
     * msg[0]:类型，可以在msgType.getType()取得类型再判断
     * @return
     */
    @Override
    public void run() {
        if(socket == null){init();}
        sendMsg(new NetMsg(MsgTypeEnum.GETUSERNUM));
        while(isRunning)
        {//等待输入和输出

            try{
                Thread.sleep(ServerConsts.SLEEP_MILLIS);
                NetMsg msg = (NetMsg) input.readUnshared();
                switch (msg.getMsgType())
                {
                    case LINKACK :
                        System.out.println(msg.getArgs()[0]);
                        break;
                    case RETUSERNUM:
                        msgReciver.sendMsg(msg);
                        System.out.println("当前人数："+msg.getArgs()[0]);
                        break;
                    default:
                        System.out.println(msg.getMsgType().name());
                        msgReciver.sendMsg(msg);
                        break;
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }

        }
    }
}
